
package com.safebox.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.safebox.R;
import com.safebox.database.DatabaseHandler;
import com.safebox.database.DatabaseHelper;
import com.safebox.database.model.Account;
import com.safebox.utils.DialogUtils;

public class RegisterActivity extends Activity {
    public static final String TAG = "RegisterActivity";

    private EditText mUsername;

    private EditText mPassword;

    private EditText mConfirmPwd;

    private RegisterTask mRegisterTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.screen_register);
        setTitle(R.string.str_register);

        mUsername = (EditText) findViewById(R.id.edit_username_reg);
        mPassword = (EditText) findViewById(R.id.edit_password_reg);
        mConfirmPwd = (EditText) findViewById(R.id.edit_password_confirm);

        findViewById(R.id.button_register_reg).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String username = mUsername.getText().toString().trim();
                String password = mPassword.getText().toString();
                String confirmPwd = mConfirmPwd.getText().toString();

                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)
                        || TextUtils.isEmpty(confirmPwd)) {
                    DialogUtils.showFailedDialog(RegisterActivity.this,
                            getResources().getString(R.string.str_register_error), getResources()
                                    .getString(R.string.str_register_error_empty));
                } else if (!confirmPwd.equals(password)) {
                    DialogUtils.showFailedDialog(RegisterActivity.this,
                            getResources().getString(R.string.str_register_error), getResources()
                                    .getString(R.string.str_register_pwd_error));
                } else {
                    mRegisterTask = new RegisterTask();
                    mRegisterTask.execute(username, password);
                }

            }
        });

        findViewById(R.id.button_cancel_reg).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterActivity.this.finish();
            }
        });
    }

    private class RegisterTask extends AsyncTask<String, Void, Integer> {
        public static final int ERROR = 0;

        public static final int SAME_USERNAME_ERROR = 1;

        public static final int SUCCESS = 2;

        private String username;

        private String password;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            DialogUtils.showProgressBarDialog(RegisterActivity.this,
                    getResources().getString(R.string.str_register_in_progress));
            
            DialogUtils.mProgressDialog.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    if (mRegisterTask != null) {
                        mRegisterTask.cancel(true);
                    }
                }
            });

        }

        @Override
        protected Integer doInBackground(String... params) {
            username = params[0];
            password = params[1];

            String[] columns = new String[]{DatabaseHelper.AccountsColumns.ACCOUNT_ID};
            String select = DatabaseHelper.AccountsColumns.USERNAME + "='" + username + "'";
            Cursor cur = DatabaseHandler.getInstance(RegisterActivity.this).query(
                    DatabaseHelper.Tables.ACCOUNTS, columns, select, null, null, null, null);
            int count = cur.getCount();
            cur.close();
            if (count > 0) {
                
                return SAME_USERNAME_ERROR;
            } else if (count == 0) {
                //insert username, password
                DatabaseHandler.getInstance(RegisterActivity.this).insert(
                        new Account(username, password));
                return SUCCESS;
            } else {
                Log.e(TAG, "RegisterTask:database query " + DatabaseHelper.Tables.ACCOUNTS
                        + " using " + username + " error");
               
                return ERROR;
            }

        }

        @Override
        protected void onPostExecute(Integer result) {
            DialogUtils.dismissProgressBar();
            switch (result) {
                case SUCCESS:
                    RegisterActivity.this.finish();
                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                    intent.putExtra("username", username);
                    startActivity(intent);
                    break;
                case SAME_USERNAME_ERROR:
                    DialogUtils.showFailedDialog(RegisterActivity.this,
                            getResources().getString(R.string.str_register_error), getResources()
                                    .getString(R.string.str_register_error_repeated_username));
                    break;
                default:
                    DialogUtils.showFailedDialog(RegisterActivity.this,
                            getResources().getString(R.string.str_register_error), getResources()
                                    .getString(R.string.str_register_error));
                    return;
            }
            return;

        }

    }

}
